package edu.uic.ids517.servlet;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import edu.uic.ids517.model.DatabaseAccessBean;
import edu.uic.ids517.model.DisplayTableBean;

public class DisplayTableServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 

		System.out.println("DisplayTableServlet");
		String nextUrl = "/displayTable.jsp";	
		HttpSession session = request.getSession();
		ResultSet result ;
		String defaultHtml = "suman";
		request.setAttribute("htmlCode", defaultHtml);

		/***   DB Access Bean  ****/
		DatabaseAccessBean dbase = (DatabaseAccessBean) session.getAttribute("dbaseBean");
		DisplayTableBean displayTable = (DisplayTableBean) session.getAttribute("displayTableBean");

		System.out.println("DisplayTableBean:     " +request.getParameter("tableName"));
		displayTable.setTableName(request.getParameter("tableName"));

		dbase.setDisplayBean(displayTable);
		result = dbase.executeDisplaySQL();
		String str = "";
		try {
			str = dbase.write(result).toString();
		} catch (SQLException e) {
			System.out.println("Exception caught converting ResultSet to HTML String");
			e.printStackTrace();
		}	
		request.setAttribute("htmlCode", str);

		RequestDispatcher dispatcher = request.getRequestDispatcher(nextUrl); 
		dispatcher.forward(request, response);


	}

}
